package com.tanhua.sso.service;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.tanhua.common.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
public class MyCenterService {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 修改手机号- 1 发送短信验证码
     *
     * @param token
     */
    public Boolean sendVerificationCode( String token) {
        // 校验token
        User user = this.userService.queryUserByToken(token);
        if(ObjectUtil.isEmpty(user)){
            return false;
        }

        String code = "654321";
        String redisKey = "CHECK_CODE_" + user.getMobile();
        redisTemplate.opsForValue().set(redisKey,code, Duration.ofMinutes(5));
        return true;
    }

    /**
     * 修改手机号 - 2 校验验证码
     *
     * @param code
     * @param token
     * @return
     */
    public Boolean checkVerificationCode(String code, String token) {
        // 校验token
        User user = this.userService.queryUserByToken(token);
        if(ObjectUtil.isEmpty(user)){
            return false;
        }

        // token有效
        // 获取redis中的key值
        String redisKey = "CHECK_CODE_" + user.getMobile();
        // 根据key获取value
        String redisCode = (String) this.redisTemplate.opsForValue().get(redisKey);
        // 校验验证码是否一致
        if(StrUtil.equals(code,redisCode)){
            // 验证码一致
            // 需要删除已经使用的验证码
            this.redisTemplate.delete(redisKey);
            return true;
        }
        return false;
    }

    /**
     * 保存手机号
     *
     * @param newPhone
     * @param token
     */
    public Boolean savePhoneNumber(String newPhone, String token) {
        // 校验token
        User user = this.userService.queryUserByToken(token);
        if(ObjectUtil.isEmpty(user)){
            return false;
        }

        // 调用手机号更新方法
        Boolean flag = this.userService.updatePhoneNumber(user.getId(), newPhone);
        if(flag){
            // 根据redisKey删除redis存储的原手机号信息
            String redisKey = "TANHUA_USER_MOBILE_" + user.getId();
            this.redisTemplate.delete(redisKey);
        }
        return flag;
    }

}
